from bcat.error import InvalidArgumentError
from bcat.api.net.service import Service, ServiceHandler
import logging

from bcat.api.impl.c.capi import CApiInstance

class ServiceImpl(Service):
    def on_before_run(self, ctx):
        if self.handler() is not None:
            self.handler().on_before_run()

    def on_after_stop(self, ctx):
        if self.handler() is not None:
            self.handler().on_after_stop()

    def __init__(self, handler):
        super(ServiceImpl, self).__init__(handler)

        self.__api = CApiInstance.get()
        self.__impl = self.__api.service_create(self.on_before_run, self.on_after_stop, None)

    def destroy(self):
        if self.__impl is not None:
            self.__api.service_destroy(self.__impl)
            self.__impl = None
        
    def __del(self):
        self.destroy()

    def run(self):
        if self.__impl is None:
            raise InvalidArgumentError("impl handle None")
        return self.__api.service_run(self.__impl)

    def is_running(self):
        if self.__impl is None:
            raise InvalidArgumentError("impl handle None")
        return self.__api.service_is_running(self.__impl)

    def stop(self):
        if self.__impl is None:
            raise InvalidArgumentError("impl handle None")
        return self.__api.service_stop(self.__impl)

    def api(self):
        return self.__api
    def impl(self):
        return self.__impl

